<?php

/**
 * @author gbfun <gbfun@163.com>  2018-05-28 16:35
 * http://www.wuweiyou.com
 */

class wwy_captcha_handler
{ 
    protected static $_instance = null;
    
    private function __clone()
    {
    }
    
    /**
     * @return wwy_captcha_handler
     */
    public static function get_instance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();    //by gbfun 又是静态变量
        }
    
        return self::$_instance;
    }
    
    protected function __construct()
    {
        
    }
	
    /**
     * 生成验证码【字符串】
     */
	public function generate_code($length = 4) 
	{
	    $characters_range = array(
	        '2', '3', '4', '5', '6', '7', '8', '9', 
	        'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 
	        'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'	        
	    ) ;
	    $count        = count($characters_range);
	    $max_position = $count - 1;
	    
	    $code = '';
	    for ($i = 0; $i < $length; $i++) {
	        $mt_rand_position = mt_rand(0, $max_position);
	        $code .= $characters_range[$mt_rand_position];	        
	    }
	    
	    return $code;
	}
	
	/**
	 * 生成并【输出】图片
	 */
	public function generate_image($font_path, $code, $width = 120, $height=40)
	{	    	    
	    //var_dump($font_path); exit();
	    
	    /* font size will be 75% of the image height */	    
	    //$font_size = $height * 0.75;
	    $font_size = $height * 0.55;
	    
	    $image = imagecreatetruecolor($width, $height);
	    
	    /* set the colours */
	    $background_color = imagecolorallocate($image, 255, 255, 255);
	    imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
        $text_color = imagecolorallocate($image, 20, 40, 100);
        $noise_color = imagecolorallocate($image, 100, 120, 180);
        
        /* generate random dots in background */
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
        }
        
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $font_path, $code);
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_path , $code);
        
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);     
	}	
}
